<template>
	<view class="container">
		<view class="header">
			<view class="title">考试记录</view>
		</view>
		
		<!-- 考试统计 -->
		<view class="statistics-section">
			<view class="stat-item">
				<text class="stat-value">{{statistics.totalCount || 0}}</text>
				<text class="stat-label">总考试次数</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{statistics.passCount || 0}}</text>
				<text class="stat-label">通过次数</text>
			</view>
			<view class="stat-item">
				<text class="stat-value">{{statistics.avgScore || 0}}</text>
				<text class="stat-label">平均分数</text>
			</view>
		</view>
		
		<scroll-view 
			scroll-y 
			class="record-list"
			refresher-enabled
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- 空状态展示 -->
			<view class="empty-state" v-if="recordList.length === 0">
				<image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
				<view class="empty-text">暂无考试记录</view>
				<view class="empty-desc">完成考试后，您的记录将会显示在这里</view>
			</view>
			
			<!-- 考试记录列表 -->
			<view class="record-item" v-for="(item, index) in recordList" :key="index" v-else>
				<view class="item-info" @click="viewExamResult(item)">
					<view class="item-title">
						<text>{{item.exam_title || (item.examInfo && item.examInfo.title) || '未命名考试'}}</text>
					</view>
					<view class="score-status-row">
						<view class="score-display">
							<text class="score-value">{{item.score}}分</text>
						</view>
						<view class="status-badge" :class="{'pass': item.is_pass, 'fail': !item.is_pass}">
							{{item.is_pass ? '通过' : '未通过'}}
						</view>
					</view>
					<view class="item-detail">
						<text class="item-label">总题数:</text>
						<text>{{item.total_questions}}</text>
					</view>
					<view class="item-detail">
						<text class="item-label">正确:</text>
						<text>{{item.correct_count}}</text>
					</view>
					<view class="item-detail">
						<text class="item-label">用时:</text>
						<text>{{formatDuration(item.duration)}}</text>
					</view>
					<view class="item-detail">
						<text class="item-label">日期:</text>
						<text>{{formatDate(item.create_date)}}</text>
					</view>
					<view class="item-detail">
						<text class="item-label">分数:</text>
						<text class="score-value">{{item.score}}</text>
						<text class="score-unit">分</text>
					</view>
					<view class="item-detail">
						<text class="item-label">状态:</text>
						<text class="item-status" :class="{'pass': item.is_pass, 'fail': !item.is_pass}">
							{{item.is_pass ? '通过' : '未通过'}}
						</text>
					</view>
				</view>
				
				<view class="item-actions">
					<view class="action-btn" @click.stop="viewExamResult(item)">
						<text class="action-text">查看详情</text>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<text class="load-text" @click="loadMore">加载更多</text>
			</view>
			
			<!-- 底部提示 -->
			<view class="bottom-tip" v-if="!hasMore && recordList.length > 0">
				<text class="tip-text">没有更多内容了</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				recordList: [],
				statistics: {
					totalCount: 0,
					passCount: 0,
					avgScore: 0
				},
				page: 1,
				pageSize: 10,
				hasMore: true,
				isLoading: false,
				isRefreshing: false
			}
		},
		onLoad() {
			// 获取考试统计
			this.getExamStatistics();
			
			// 获取考试记录列表
			this.getExamRecords();
		},
		methods: {
			// 获取考试统计
			async getExamStatistics() {
				try {
					// 调用云对象获取考试统计
					const examService = uniCloud.importObject('exam-service');
					const res = await examService.getExamStatistics();
					
					if (res.code === 0) {
						this.statistics = res.data;
						} else {
						// 如果云对象不可用，使用模拟数据
						this.getMockStatistics();
					}
				} catch (err) {
					console.error('获取考试统计失败', err);
					// 如果云对象不可用，使用模拟数据
					this.getMockStatistics();
				}
			},
			
			// 获取模拟考试统计
			getMockStatistics() {
				this.statistics = {
					totalCount: 8,
					passCount: 6,
					avgScore: 85
				};
			},
			
			// 获取考试记录列表
			async getExamRecords(loadMore = false) {
				try {
					this.isLoading = true;
					
					// 调用云对象获取考试记录
					const examService = uniCloud.importObject('exam-service');
					const result = await examService.getExamRecords({
							page: this.page,
							pageSize: this.pageSize
					});
					
					const data = result && result.data;
					
					if (data && data.length) {
						if (loadMore) {
							this.recordList = [...this.recordList, ...data];
						} else {
							this.recordList = data;
						}
						this.hasMore = data.length >= this.pageSize;
					} else {
						if (!loadMore) {
							this.recordList = [];
						}
						this.hasMore = false;
						
						// 如果没有真实数据，使用模拟数据
						if (this.recordList.length === 0) {
							this.getMockExamRecords(loadMore);
						}
					}
					
					return Promise.resolve();
				} catch (e) {
					console.error('获取考试记录失败:', e);
					
					// 加载失败时显示模拟数据
					this.getMockExamRecords(loadMore);
					
					uni.showToast({
						title: '获取考试记录失败，显示模拟数据',
						icon: 'none'
					});
					
					return Promise.reject(e);
				} finally {
					this.isLoading = false;
					this.loading = false;
				}
			},
			
			// 获取模拟考试记录列表
			getMockExamRecords(loadMore = false) {
				// 模拟数据
				const mockData = [
					{
						_id: '1',
						exam_id: '101',
						exam_title: '足球裁判基础规则考试',
						score: 90,
						is_pass: true,
						total_questions: 20,
						correct_count: 18,
						duration: 1500, // 25分钟
						create_date: new Date('2023-06-15').getTime()
					},
					{
						_id: '2',
						exam_id: '102',
						exam_title: '足球越位规则专项考试',
						score: 75,
						is_pass: true,
						total_questions: 10,
						correct_count: 7.5,
						duration: 900, // 15分钟
						create_date: new Date('2023-06-20').getTime()
					},
					{
						_id: '3',
						exam_id: '103',
						exam_title: '足球裁判手势信号考试',
						score: 60,
						is_pass: false,
						total_questions: 15,
						correct_count: 9,
						duration: 1200, // 20分钟
						create_date: new Date('2023-06-25').getTime()
					},
					{
						_id: '4',
						exam_id: '104',
						exam_title: '足球比赛规则综合考试',
						score: 95,
						is_pass: true,
						total_questions: 30,
						correct_count: 28.5,
						duration: 2400, // 40分钟
						create_date: new Date('2023-07-01').getTime()
					}
				];
				
				// 模拟分页
				const startIndex = (this.page - 1) * this.pageSize;
				const endIndex = startIndex + this.pageSize;
				const pageData = mockData.slice(startIndex, endIndex);
				
				if (loadMore) {
					this.recordList = [...this.recordList, ...pageData];
				} else {
					this.recordList = pageData;
				}
				
				this.hasMore = endIndex < mockData.length;
			},
			
			// 加载更多
			loadMore() {
				if (!this.hasMore || this.isLoading) return;
				
				this.page++;
				this.getExamRecords(true);
			},
			
			// 查看考试结果
			viewExamResult(item) {
				uni.navigateTo({
					url: `/pages/exam/exam-result?id=${item._id}`
				});
			},
			
			// 格式化日期
			formatDate(timestamp) {
				if (!timestamp) return '';
				
				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				return `${year}-${month}-${day}`;
			},
			
			// 格式化时长（秒 -> 分:秒）
			formatDuration(seconds) {
				if (!seconds) return '0分钟';
				
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = seconds % 60;
				
				if (remainingSeconds === 0) {
					return `${minutes}分钟`;
				} else {
					return `${minutes}分${remainingSeconds}秒`;
				}
			},
			
			// 添加刷新方法
			onRefresh() {
				this.isRefreshing = true;
				
				// 重置页码
				this.page = 1;
				
				// 调用获取记录函数
				Promise.all([
					this.getExamStatistics(),
					this.getExamRecords(false)
				]).then(() => {
					setTimeout(() => {
						this.isRefreshing = false;
					}, 800);
				}).catch(err => {
					console.error('刷新考试记录失败:', err);
					this.isRefreshing = false;
					uni.showToast({
						title: '刷新失败，请稍后再试',
						icon: 'none'
					});
				});
			}
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.isRefreshing = true;
			this.getExamStatistics();
			
			this.page = 1;
			this.recordList = [];
			this.hasMore = true;
			this.getExamRecords();
			
			setTimeout(() => {
				uni.stopPullDownRefresh();
				this.isRefreshing = false;
			}, 1000);
		},
		// 触底加载更多
		onReachBottom() {
			this.loadMore();
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #F5F5F5;
		display: flex;
		flex-direction: column;
	}
	
	/* 头部样式 */
	.header {
		padding: 30rpx;
		background-color: #1BAE76;
		color: #FFFFFF;
	}
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
	}
	
	/* 统计区域样式 */
	.statistics-section {
		display: flex;
		justify-content: space-around;
		padding: 30rpx;
		background-color: #FFFFFF;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.stat-value {
		font-size: 44rpx;
		font-weight: bold;
		color: #1BAE76;
		margin-bottom: 10rpx;
	}
	
	.stat-label {
		font-size: 26rpx;
		color: #666666;
	}
	
	/* 空状态样式 */
	.empty-box {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 120rpx 0;
	}
	
	.empty-icon {
		width: 220rpx;
		height: 220rpx;
		margin-bottom: 30rpx;
		opacity: 0.8;
	}
	
	.empty-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #666666;
		margin-bottom: 16rpx;
	}
	
	.empty-tips {
		font-size: 26rpx;
		color: #999999;
	}
	
	/* 记录列表样式 */
	.record-list {
		flex: 1;
		padding: 0 30rpx;
		box-sizing: border-box;
		height: calc(100vh - 280rpx);
	}
	
	.record-item {
		background-color: #FFFFFF;
		padding: 30rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.08);
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}
	
	.item-info {
		flex: 1;
	}
	
	.item-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 16rpx;
		line-height: 1.4;
	}
	
	.item-detail {
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 8rpx;
		display: flex;
		align-items: center;
	}
	
	.item-label {
		color: #999999;
		margin-right: 10rpx;
	}
	
	.score-value {
		font-weight: bold;
		color: #1BAE76;
	}
	
	.item-actions {
		margin-left: 20rpx;
		margin-right: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	
	.action-btn {
		padding: 10rpx 24rpx;
		border-radius: 30rpx;
		background-color: #1BAE76;
		box-shadow: 0 4rpx 8rpx rgba(27, 174, 118, 0.2);
		min-width: 160rpx;
		text-align: center;
	}
	
	.action-btn.view {
		background-color: #1BAE76;
	}
	
	.action-text {
		font-size: 28rpx;
		color: #FFFFFF;
		font-weight: bold;
	}
	
	/* 加载更多样式 */
	.load-more {
		text-align: center;
		padding: 36rpx 0;
	}
	
	.load-text {
		font-size: 28rpx;
		color: #1BAE76;
		font-weight: bold;
		padding: 12rpx 36rpx;
		border-radius: 30rpx;
		background-color: rgba(27, 174, 118, 0.1);
	}
	
	/* 底部提示样式 */
	.bottom-tip {
		text-align: center;
		padding: 30rpx 0;
	}
	
	.tip-text {
		font-size: 26rpx;
		color: #999999;
	}
	
	.score-status-row {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}
	
	.score-display {
		margin-right: 20rpx;
	}
	
	.status-badge {
		font-size: 24rpx;
		padding: 4rpx 16rpx;
		border-radius: 20rpx;
	}
	
	.status-badge.pass {
		color: #1BAE76;
		background-color: rgba(27, 174, 118, 0.1);
	}
	
	.status-badge.fail {
		color: #FF3B30;
		background-color: rgba(255, 59, 48, 0.1);
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 10rpx;
	}
	
	.empty-desc {
		font-size: 28rpx;
		color: #999999;
	}
</style> 